<?php
namespace Common\Controller;
use Common\Controller\BaseController;

/**
 * 站长后台基类
 */
class AdminController extends BaseController
{
	public $educationItems     = [1 =>'小学及以下','初中','高中','大专','本科','硕士研究生及以上'];//学历

	public $houseTypeItems     = ['无','商品房无贷款','商品房有贷款','自建房','房改房','租房','拆迁安置房','单位宿舍','商铺有贷款','商铺无贷款','公租',];//房屋类型

	public $creditQ            = ['妈妈的名字','小学的名字'];//信用卡问题

	public $companyNatureItems = ['自由职业','个体经济','股份公司','国家机关','事业单位','外资或合资公司','民营企业'];//单位性质

	public $maritalStatusItems = ['未婚','离异','丧偶','已婚有子女','已婚无子女'];//婚姻状态

	public $serviceSourceItems = ['4S店','二级经销商','二手车经销商','租赁公司','其他'];//业务来源

	public $relationship       = ['父亲','母亲','哥哥','姐姐','祖父','祖母','外祖父','外祖母','兄弟','姐妹','兄妹','姐弟','朋友','儿子','女儿','妻子'];//紧急联系人关系

	public $distributorItems   = ['无','签约经销商'];//经销商类别

	public $carFirmItems       = ['简易贷','标准贷','租赁'];//业务类型

	public $carTypeItems       = ['国产车','进口车'];//车辆类型

	public $carModelItems      = ['新车','二手车','存量车','商用车',];//车辆性质

	public $onCardItems        = ['私牌','公牌'];//上牌类型

	public $yearLimitItems     = ['一年' => 12,'二年' => 24,'三年' => 36,'四年' => 48,'五年' => 60];//年限

	public $fileTypeItems	   = ['主贷人','配偶','担保人'];

	public $workYearItems      = ['无','3年以下','3年-5年','5年及以上'];//工作年限

	public $statusItems        = ['征信待提交', '征信待审核', '申请待审核', '删除', '央行征信通过','拒绝贷款', '公检法审核通过', 9 => '审核不通过', 10 =>'审核已完成', 901 => '央行征信不通过', 902 => '公检法审核不通过'];

	/**
     * [uploadAliyunOss 第三方存储]
     * @param  [type] $p_file [二进制文件流上传的文件地址]
     * @return [type]         [第三方存储地址]
     */
    protected function uploadAliyunOssWithBinary($p_filename)
    {
        $accessKeyId     = "LTAIkIwLvGP6mIP8"; ;
        $accessKeySecret = "bIl02FSrHbKu0uu12ewYUSC02U4aCc";
        $endpoint        = "oss-cn-hangzhou.aliyuncs.com";
        $bucket          = "ronjoy";

        $object = $p_filename;
        $content = "Hi, OSS.";
        try {
            $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
            // $ossClient->createBucket($bucket);
            $ossClient->putObject($bucket, $object, $content);

            $ret = $ossClient->uploadFile($bucket, $object, $p_filename);

            unlink($p_filename);
        } catch (OssException $e) {
            print $e->getMessage();
        }

        return $ret['info']['url'];
    }

    /**
     * [uploadAliyunOss 第三方存储]
     * @param  [type] $p_file [file文件的name值]
     * @return [type]         [第三方存储地址]
     */
    protected function uploadAliyunOss($p_file)
    {
        $accessKeyId     = "LTAIkIwLvGP6mIP8"; ;
        $accessKeySecret = "bIl02FSrHbKu0uu12ewYUSC02U4aCc";
        $endpoint        = "oss-cn-hangzhou.aliyuncs.com";
        $bucket          = "ronjoy";

        // 允许上传的图片后缀
        $allowedExts = array("gif", "jpeg", "jpg", "png","mp4","mov","JPG","GIF","JPEG","PNG","MP4","MOV","PDF","pdf");
        $temp        = explode(".", $_FILES[$p_file]["name"]);
        $extension   = end($temp);     // 获取文件后缀名

        if ((($_FILES[$p_file]["type"] == "image/gif")
            || ($_FILES[$p_file]["type"] == "image/jpeg")
            || ($_FILES[$p_file]["type"] == "image/jpg")
            || ($_FILES[$p_file]["type"] == "image/pjpeg")
            || ($_FILES[$p_file]["type"] == "image/x-png")
            || ($_FILES[$p_file]["type"] == "image/png")
            || ($_FILES[$p_file]["type"] == "application/pdf"))
        )
        {
            if($_FILES[$p_file]["size"] >= 2097152)   // 2m图片不允许传
            {
                $this->error('上传的文件超过2M');
            }

        }

        if ($_FILES[$p_file]["type"] == "video/mp4" || $_FILES[$p_file]["type"] == "video/quicktime")
        {
            if($_FILES[$p_file]["size"] >= 209715200)   // 200m图片不允许传
            {
                $this->error('上传的视频超过200M');
            }
        }

        if ((($_FILES[$p_file]["type"] == "image/gif")
        || ($_FILES[$p_file]["type"] == "video/mp4")
        || ($_FILES[$p_file]["type"] == "video/quicktime")
        || ($_FILES[$p_file]["type"] == "image/jpeg")
        || ($_FILES[$p_file]["type"] == "image/jpg")
        || ($_FILES[$p_file]["type"] == "image/pjpeg")
        || ($_FILES[$p_file]["type"] == "image/x-png")
        || ($_FILES[$p_file]["type"] == "application/pdf")
        || ($_FILES[$p_file]["type"] == "image/png"))
        && in_array($extension, $allowedExts))
        {
            if ($_FILES[$p_file]["error"] > 0)
            {
                $this->error($_FILES[$p_file]["error"]);
            }
            else
            {
                // 判断当期目录下的 upload 目录是否存在该文件
                // 如果没有 upload 目录，你需要创建它，upload 目录权限为 777
                if (file_exists("upload/" . $_FILES[$p_file]["name"]))
                {
                    $this->error($_FILES[$p_file]["name"] . " 文件已经存在。 ");
                    }
                else
                {
                    // 如果 upload 目录不存在该文件则将文件上传到 upload 目录下
                    $strFilename = uniqid().'.'.$extension;
                    move_uploaded_file($_FILES[$p_file]["tmp_name"], $strFilename);
                    // echo "文件存储在: " .  $strFilename;
                }
            }
        } else {
            $this->error('非法的文件格式');
        }

        $object = $strFilename;

        $content = "Hi, OSS.";

        try {
            $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->createBucket($bucket);
            $ossClient->putObject($bucket, $object, $content);

            $ret = $ossClient->uploadFile($bucket, $object, $strFilename);
            // 图片缩放
            // $options = array(
            //     \OSS\OssClient::OSS_FILE_DOWNLOAD => $strFilename,
            //     \OSS\OssClient::OSS_PROCESS => "image/resize,m_fixed,h_100,w_100" );
            // $ossClient->getObject($bucket, $object, $options);

            unlink($strFilename);
        } catch (OssException $e) {
            print $e->getMessage();
        }

        return $ret['info']['url'];
    }

	/**
	 * [根据areaId获取对应省市县]
	 * @param  [type] $p_areaId [地区ID]
	 * @return [type]           [含有省市县的数组]
	 * @author [ NYJ]
	 */
	protected function getAreaInfo($p_areaId = 110000)
	{
		if (is_null($p_areaId) || !is_numeric($p_areaId))
		{
			$p_areaId = 110000;
		}

		$district = $p_areaId;
		$city     = floor($district/100)*100;
		$province = floor($district/10000)*10000;

		$area_where = 'area_id = '.$district.' or area_id = '.$city.' or area_id = '.$province;
		$_tmp = $this->getList('area_id,area_name','area',$area_where);

		switch (count($_tmp))
		{
			case 1:
				$_tmp['province'] = $_tmp[0]['area_name'];
				$_tmp['city']     = '';
				$_tmp['district'] = '';
				unset($_tmp[0]);
				break;

			case 2:
				$_tmp['province'] = $_tmp[0]['area_name'];
				$_tmp['city']     = $_tmp[1]['area_name'];
				$_tmp['district'] = '';
				unset($_tmp[0],$_tmp[1]);
				break;

			case 3:
				$_tmp['province'] = $_tmp[0]['area_name'];
				$_tmp['city']     = $_tmp[1]['area_name'];
				$_tmp['district'] = $_tmp[2]['area_name'];
				unset($_tmp[0],$_tmp[1],$_tmp[2]);
				break;
		}

		return $_tmp;
	}
	protected function _initialize()
	{
		parent::_initialize();
		// 验证用户登录
		if(!session('?adminInfo.id')){
			session('[destroy]');
			$this->redirect('Admin/Public/index');
		}
		// 是否启用认证
		//$authCheck = false;
		if(session('adminInfo.id')==1){
          $authCheck = false;
		}else{
		  $authCheck = true;
		}
		if($authCheck){
			// 无需认证模块
			$noCheck = array('Index/index', 'Index/main','Index/My_wait','Check/not_index');
			if(!$this->authCheck(CONTROLLER_NAME.'/'.ACTION_NAME, $noCheck)){
				if(IS_AJAX){
					$this->returnResult(true, '没有权限');
				}else{
					exit('没有权限');
				}
			}
		}
		// 获取左侧菜单
		$menu = session('left_menu');
		if(!$menu)
		{
			$menuList = $this->getList('id,pid,title,name,type', 'node', 'status=1 and type<2 and id in (' . session('adminInfo.rules') . ')', 'sort desc,id asc');

			foreach($menuList as $k => $v)
			{
				if($v['pid'] == 0)
				{
					$menu[$k] = $v;
					foreach($menuList as $key => $value)
					{
						if(session('adminInfo.gpid')!=0)
						{
				             $where=' gpid='.session('adminInfo.gpid');
						}else{
							$where = ' 1=1';
						}

						if(session('remark') == '业务员'){
							$where .=' and admin_id='.session('id');
						}

						if($value['pid']==68)
						{
                           switch ($value['id']) {
                           	case '70'://征信待提交
                           		$value['count']=M('user')->where('check_status=-5 and  '.$where)->count();
                           		break;
                           	case '71'://申请待提交
                           		$value['count']=M('user')->where('check_status=-1 and status=1 and'.$where)->count();
                           		break;
                           	case '73'://申请待审核
                           		$value['count']=M('user')->where('check_status>-1 and check_status<6 and '.$where)->count();
                           		break;
                           	case '74'://申请退回
                           		$value['count']=M('user')->where('(status=12 or status=901 or status=902) and check_status<=6 and '.$where)->count();
                           		break;
                           	case '75'://申请拒绝
                           		$value['count']=M('user')->where('status=5 and '.$where)->count();
                           		break;
                           	case '76'://申请作废
                           		$value['count']=M('user')->where('status=3 and '.$where)->count();
                           		break;
                             case '130'://征信待审核
                             	$value['count']=M('user')->where('check_status=-4 and '.$where)->count();
                             	break;
                             case '189'://申请已待定
                             	$value['count']=M('user')->where('status=9 and '.$where)->count();
                             	break;
                           	default:
                           		break;
                           }
						}
						$value['pid'] == $v['id'] && $menu[$k]['sub'][] = $value;
					}
				}
			}
			//session('left_menu', $menu);
		}
		/*print_r($menu);
		exit;*/
		$this->assign('menuList', $menu);
	}

	/**
	 * 检查关键字是否存在
	 * @param string $keyword 关键字
	 * @param number $pid 项目ID
	 * @param string $module 模块名
	 *        zhangxinhe 2015-12-23
	 */
	public function checkKeyword($keyword, $pid = 0)
	{
		$info = M('keyword')->field('id,pid')->where(array('keyword' => trim($keyword)))->find();
		if($info['id'] > 0 && ($pid == 0 || $info['pid'] != $pid)){
			$this->returnResult(false, array('', '关键字已存在！'));
		}
	}

	/**
	 * 设置关键字
	 * @param string $module 内容模块
	 * @param integer $pid 内容ID
	 * @param number $act 操作 1添加 2修改 3删除
	 * @param string $keyword 关键字
	 *        zhangxinhe 2015-1-29
	 */
	public function setKeyword($module, $pid, $act = 3, $keyword = '')
	{
		$keyword = trim($keyword);
		if($act == 1){
			return M('keyword')->add(array('module' => $module, 'pid' => $pid, 'keyword' => $keyword));
		}elseif($act == 2){
			return M('keyword')->where(array('module' => $module, 'pid' => $pid))->save(array('keyword' => $keyword));
		}else{
			return M('keyword')->where(array('module' => $module, 'pid' => $pid))->delete();
		}
	}

	/**
	 * 快捷状态设置
	 * zhangxinhe Dec 25, 2015
	 */
	public function setStatus()
	{
		$status = I('get.status', 0, 'intval');
		$result = M(CONTROLLER_NAME)->where('id=' . I('get.id', 0, 'intval'))->setField('status', ($status == 1 ? 0 : 1));
		$this->returnResult($result);
	}

	/**
	 * 快捷排序设置
	 * zhangxinhe Dec 25, 2015
	 */
	public function setSort(){
		$sort = I('get.sort', 100, 'intval');
		$result = M(CONTROLLER_NAME)->where('id=' . I('get.id', 0, 'intval'))->setField('sort', $sort);
		$this->returnResult($result);
	}

	/**
	 * 权限验证
	 * @param string $name 规则名称
	 * @param array $noCheck 无需验证模块
	 * @param number $type 验证类型 1 实时验证 2 登录验证
	 *        zhangxinhe 2015-12-25
	 */
	private function authCheck($name, $noCheck = array(), $type = 1)
	{
		$aid = session('adminInfo.id');
		if(empty($name) || $aid <= 0){
			return false;
		}elseif($aid == 2 || in_array($name, $noCheck)){
			return true;
		}elseif($type == 2 && session('AUTH_LIST')){
			return in_array($name, session('AUTH_LIST'));
		}else{
			$info = $this->getInfo('g.rules', array('group g', 'admins a'), 'a.gid=g.id and a.id=' . $aid);
			if($info['rules']){
				if($type == 2){
					$rulesName = M('node')->where('status=1 and id in (' . $info['rules'] . ')')->getField('name', true);
					session('AUTH_LIST', $rulesName);
					return in_array($name, $rulesName);
				}else{
					$rulesArr = explode(',', $info['rules']);
					$rulesId = M('node')->where('status=1 and name="' . $name . '"')->getField('id');
					return in_array($rulesId, $rulesArr);
				}
			}
			return false;
		}
	}
}
?>